//app.js
import api from 'utils/api.js'
var loginInfo = {};
App({
  setConfig: { url: 'https://chengyu.xingliaoapp.com/', type: 0 },
  onLaunch: function () {
    this.userLogin();
  },
  data: {
    extra: null
  },
  onShow: function (e) {
    this.data.extra = e;
  },
  globalData: {
    userInfo: null,
    token: '',
    timer: null,
    hotTitle: '',
    randCode: [

    ],
    code: null,
    defaultConfigs: null
  },
  
  doesItShow:function(){
    
  },
  //登录
  userLogin: function () {
    var that = this;
    that.doesItShow();
    var codes;
    //获取登录code
    wx.login({
      success: function (res) {
        // console.log(res.code);return false;
        if (res.code) {
          loginInfo.code = res.code;
          that.globalData.code = res.code
          codes = res.code;
          //获取用户信息
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                wx.getUserInfo({
                  success: res => {
                    // 可以将 res 发送给后台解码出 unionId
                    var infoUser = '';
                    that.globalData.userInfo = infoUser = res.userInfo;
                    // 所以此处加入 callback 以防止这种情况
                    if (that.userInfoReadyCallback) {
                      that.userInfoReadyCallback(res)
                    }
                    //用户信息入库
                    var url = that.setConfig.url + '/index.php/User/login/dologin';
                    var data = {
                      user_name: infoUser.nickName,
                      nick_name: infoUser.nickName,
                      head_img: infoUser.avatarUrl,
                      sex: infoUser.gender,
                      coutry: infoUser.country,
                      city: infoUser.city,
                      province: infoUser.province,
                      code: codes,
                      encryptedData: res.encryptedData,
                      signature: res.signature
                    }
                    that.postLogin(url, data);
                  }
                })
              } else {
                wx.authorize({
                  scope: 'scope.userInfo',
                  success: res => {
                    //用户已经同意小程序授权
                    wx.getUserInfo({
                      success: res => {
                        // 可以将 res 发送给后台解码出 unionId
                        var infoUser = '';
                        that.globalData.userInfo = infoUser = res.userInfo;
                        // 所以此处加入 callback 以防止这种情况
                        if (that.userInfoReadyCallback) {
                          that.userInfoReadyCallback(res)
                        }
                        //用户信息入库
                        var url = that.setConfig.url + '/index.php/User/login/dologin';
                        var data = {
                          user_name: infoUser.nickName,
                          nick_name: infoUser.nickName,
                          head_img: infoUser.avatarUrl,
                          sex: infoUser.gender,
                          coutry: infoUser.country,
                          city: infoUser.city,
                          province: infoUser.province,
                          code: codes,
                          encryptedData: res.encryptedData,
                          signature: res.signature
                        }
                        that.postLogin(url, data);
                      }
                    })
                  }
                })
              }
            }
          });
        } else {
          that.userLogin();
          return false;
        }
      }
    })
  },
  //提交
  postLogin: function (url, data, callback = function () { }) {
    var that = this;
    //发起网络请求
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        if (res.data.code != 20000) {
          if (res.data.code == 300001) {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false
            });
            callback(res);
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'loading',
              mask: true,
              duration: 1500
            });
          }
          if (res.data.code == 40500) { callback(res); }
          if (res.data.code == 20300) { callback(res); }
          return false;
        }
        if (res.data.token) {
          that.globalData.token = res.data.token;
          var stro_token = wx.getStorageSync('token');
          if (stro_token != res.data.token) {
            //重新处理token
            wx.setStorageSync('token', res.data.token);
            //加载全局配置选项
            wx.showLoading({
              title: '加载配置中..',
            });
            api.post('index.php?g=Api&m=GobalConf&a=getRunDataConfig', { token: res.data.token, type: that.setConfig.type }, function (res) {
              wx.hideLoading();
              if (res.code == 2000) {
                that.globalData.defaultConfigs = res.data;
                //console.log('我来看看这个时候的数据是什么');
                ///console.log(that.globalData.defaultConfigs);
              } else {
                wx.showLoading({
                  title: '加载配置文件失败',
                  duration: 1500
                })
              }
            }, false);
          }
        } else {
          wx.showToast({
            title: '授权失败请重新进入',
             mask: true,
             duration: 1500
          });
        }
        /*api.post('index.php?g=Api&m=GobalConf&a=getRunDataConfig', {
          token: that.globalData.token,
          type: that.setConfig.type
        }, (data) => {
        });*/
        callback(res);
      }
    })
  },
  onError: function (errMsg) {
    //Todo 程序出现问题（脚本发生错误，API调用失败保存错误信息）
    console.log('warning::' + msg);
  },
  wxPost: function (url, data, callback = function () { }) {
    var _this = this;
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        if (res.data.code != 20000) {
          wx.showToast({
            title: res.data.msg,
            icon: 'loading',
            mask: true,
            duration: 1500
          });
        }
        callback(res);
      }
    });
  },
  post: function (cmd, params, callback){
    /*wx.showToast({
      title: '处理中...',
      icon: 'loading',
      duration: 2000
    });*/
    var _this = this;
    var token = _this.globalData.token;
    console.log("请求地址".token);
    console.log(App + cmd);
    wx.request({
      url: _this.setConfig.url + cmd,
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: (res) => {
        wx.hideToast();
        console.log("request->" + res.data);
        /*
        const data = res.data
        if(data.code){
            wx.showModal({
                title: '提示',
                showCancel: false,
                confirmColor: 'rgb(251,93,93)',
                content: data.message,
                success: (res) => {
                }
                })
            return
        }*/
        if (typeof (callback) == 'function')
          callback(res.data);
      }
    })
  }
})
